import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, List, Tag, Button, Spin, Alert } from 'antd';
import {
  BookOutlined,
  CalendarOutlined,
  UserOutlined,
  TeamOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const Dashboard = () => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({});
  const [recentCourses, setRecentCourses] = useState([]);
  const [recentBookings, setRecentBookings] = useState([]);
  const { user, isAdmin, isTeacher, isStudent } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    loadDashboardData();
  }, [user]);

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      
      if (isAdmin()) {
        await loadAdminData();
      } else if (isTeacher()) {
        await loadTeacherData();
      } else if (isStudent()) {
        await loadStudentData();
      }
    } catch (error) {
      console.error('加载仪表板数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadAdminData = async () => {
    try {
      const [courses, bookings, students, teachers] = await Promise.all([
        apiService.getCourses(),
        apiService.getBookings(),
        apiService.getStudents(),
        apiService.getTeachers()
      ]);

      setStats({
        totalCourses: courses.length,
        totalBookings: bookings.length,
        totalStudents: students.length,
        totalTeachers: teachers.length,
        openCourses: courses.filter(c => c.status === 'OPEN').length,
        confirmedBookings: bookings.filter(b => b.status === 'CONFIRMED').length
      });

      setRecentCourses(courses.slice(0, 5));
      setRecentBookings(bookings.slice(0, 5));
    } catch (error) {
      console.error('加载管理员数据失败:', error);
    }
  };

  const loadTeacherData = async () => {
    try {
      const courses = await apiService.getCoursesByTeacher(user.relatedId);
      const allBookings = await Promise.all(
        courses.map(course => apiService.getBookingsByCourse(course.id))
      );
      const bookings = allBookings.flat();

      setStats({
        myCourses: courses.length,
        totalBookings: bookings.length,
        openCourses: courses.filter(c => c.status === 'OPEN').length,
        confirmedBookings: bookings.filter(b => b.status === 'CONFIRMED').length
      });

      setRecentCourses(courses.slice(0, 5));
      setRecentBookings(bookings.slice(0, 5));
    } catch (error) {
      console.error('加载教师数据失败:', error);
    }
  };

  const loadStudentData = async () => {
    try {
      const [courses, bookings] = await Promise.all([
        apiService.getCoursesPublic(),
        apiService.getBookingsByStudent(user.relatedId)
      ]);

      setStats({
        availableCourses: courses.filter(c => c.status === 'OPEN').length,
        myBookings: bookings.length,
        confirmedBookings: bookings.filter(b => b.status === 'CONFIRMED').length,
        pendingBookings: bookings.filter(b => b.status === 'PENDING').length
      });

      setRecentCourses(courses.filter(c => c.status === 'OPEN').slice(0, 5));
      setRecentBookings(bookings.slice(0, 5));
    } catch (error) {
      console.error('加载学生数据失败:', error);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'OPEN':
        return 'green';
      case 'FULL':
        return 'orange';
      case 'CLOSED':
        return 'red';
      case 'CONFIRMED':
        return 'green';
      case 'PENDING':
        return 'orange';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'OPEN':
        return '开放';
      case 'FULL':
        return '已满';
      case 'CLOSED':
        return '关闭';
      case 'CONFIRMED':
        return '已确认';
      case 'PENDING':
        return '待确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  const renderAdminStats = () => (
    <Row gutter={16}>
      <Col span={6}>
        <Card>
          <Statistic
            title="总课程数"
            value={stats.totalCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="总预约数"
            value={stats.totalBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="学生总数"
            value={stats.totalStudents}
            prefix={<TeamOutlined />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="教师总数"
            value={stats.totalTeachers}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#fa8c16' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderTeacherStats = () => (
    <Row gutter={16}>
      <Col span={6}>
        <Card>
          <Statistic
            title="我的课程"
            value={stats.myCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="开放课程"
            value={stats.openCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="总预约数"
            value={stats.totalBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="已确认预约"
            value={stats.confirmedBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#fa8c16' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderStudentStats = () => (
    <Row gutter={16}>
      <Col span={6}>
        <Card>
          <Statistic
            title="可选课程"
            value={stats.availableCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="我的预约"
            value={stats.myBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="已确认"
            value={stats.confirmedBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#722ed1' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="待确认"
            value={stats.pendingBookings}
            prefix={<CalendarOutlined />}
            valueStyle={{ color: '#fa8c16' }}
          />
        </Card>
      </Col>
    </Row>
  );

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <h1 className="page-title">仪表板</h1>
      
      <Alert
        message={`欢迎回来，${user?.username}！`}
        description={`您当前的角色是：${isAdmin() ? '管理员' : isTeacher() ? '教师' : '学生'}`}
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* 统计卡片 */}
      {isAdmin() && renderAdminStats()}
      {isTeacher() && renderTeacherStats()}
      {isStudent() && renderStudentStats()}

      {/* 最近课程和预约 */}
      <Row gutter={16} style={{ marginTop: 24 }}>
        <Col span={12}>
          <Card
            title="最近课程"
            extra={
              <Button
                type="link"
                icon={<EyeOutlined />}
                onClick={() => navigate('/courses')}
              >
                查看全部
              </Button>
            }
          >
            <List
              dataSource={recentCourses}
              renderItem={course => (
                <List.Item>
                  <List.Item.Meta
                    title={course.name}
                    description={
                      <div>
                        <div>教师: {course.teacher?.name}</div>
                        <div>时间: {moment(course.startTime).format('YYYY-MM-DD HH:mm')}</div>
                      </div>
                    }
                  />
                  <Tag color={getStatusColor(course.status)}>
                    {getStatusText(course.status)}
                  </Tag>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card
            title="最近预约"
            extra={
              <Button
                type="link"
                icon={<EyeOutlined />}
                onClick={() => navigate('/bookings')}
              >
                查看全部
              </Button>
            }
          >
            <List
              dataSource={recentBookings}
              renderItem={booking => (
                <List.Item>
                  <List.Item.Meta
                    title={booking.course?.name}
                    description={
                      <div>
                        <div>学生: {booking.student?.name}</div>
                        <div>预约时间: {moment(booking.bookingTime).format('YYYY-MM-DD HH:mm')}</div>
                      </div>
                    }
                  />
                  <Tag color={getStatusColor(booking.status)}>
                    {getStatusText(booking.status)}
                  </Tag>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;